#!/usr/bin/env node

/**
 * 依赖检查脚本
 * 用于检查项目中是否安装了所有必要的依赖
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

// 核心依赖列表
const CORE_DEPENDENCIES = [
  'vue',
  'element-plus',
  '@element-plus/icons-vue'
];

// 可选依赖列表
const OPTIONAL_DEPENDENCIES = [
  'axios',
  'dayjs',
  'lodash-es',
  'echarts', 
  'vue-router',
  '@vueuse/core',
  'vue-i18n',
  'big.js',
  'cropperjs',
  'driver.js',
  'echarts-wordcloud',
  'mitt',
  'nprogress',
  'sortablejs',
  'vue-types',
  'web-storage-cache',
  '@wangeditor/editor',
  '@wangeditor/editor-for-vue',
  '@zxcvbn-ts/core',
  '@zxcvbn-ts/language-common',
  'jsencrypt'
];

// 组件与依赖的映射关系
const COMPONENT_DEPENDENCIES = {
  'Echart': ['echarts'],
  'Editor': ['@wangeditor/editor', '@wangeditor/editor-for-vue'],
  'Cropper': ['cropperjs'],
  'Form': ['@vueuse/core']
};

/**
 * 检查依赖是否已安装
 * @param {string} dependency 依赖名称
 * @returns {boolean} 依赖是否已安装
 */
function isDependencyInstalled(dependency) {
  try {
    // 尝试解析模块路径
    require.resolve(dependency);
    return true;
  } catch (error) {
    return false;
  }
}

/**
 * 获取依赖版本
 * @param {string} dependency 依赖名称
 * @returns {string|null} 依赖版本
 */
function getDependencyVersion(dependency) {
  try {
    const packageJsonPath = require.resolve(`${dependency}/package.json`);
    const packageJson = require(packageJsonPath);
    return packageJson.version;
  } catch (error) {
    return null;
  }
}

/**
 * 主函数
 */
function main() {
  console.log('======================================');
  console.log('EPMS Element 依赖检查');
  console.log('======================================');
  
  // 检查核心依赖
  console.log('\n核心依赖:');
  let missingCore = false;
  
  CORE_DEPENDENCIES.forEach(dep => {
    const isInstalled = isDependencyInstalled(dep);
    const version = isInstalled ? getDependencyVersion(dep) : null;
    const status = isInstalled ? '✅' : '❌';
    
    console.log(`${status} ${dep}${version ? ` (v${version})` : ''}`);
    
    if (!isInstalled) {
      missingCore = true;
    }
  });
  
  // 检查可选依赖
  console.log('\n可选依赖:');
  
  OPTIONAL_DEPENDENCIES.forEach(dep => {
    const isInstalled = isDependencyInstalled(dep);
    const version = isInstalled ? getDependencyVersion(dep) : null;
    const status = isInstalled ? '✅' : '⚠️';
    
    console.log(`${status} ${dep}${version ? ` (v${version})` : ''}`);
  });
  
  // 组件依赖检查
  console.log('\n组件依赖关系:');
  
  Object.entries(COMPONENT_DEPENDENCIES).forEach(([component, deps]) => {
    console.log(`\n${component}:`);
    
    deps.forEach(dep => {
      const isInstalled = isDependencyInstalled(dep);
      const status = isInstalled ? '✅' : '⚠️';
      
      console.log(`  ${status} ${dep}`);
    });
  });
  
  console.log('\n======================================');
  
  if (missingCore) {
    console.error('❌ 缺少核心依赖，请安装后再使用EPMS Element');
    process.exit(1);
  } else {
    console.log('✅ 所有核心依赖已安装');
  }
}

// 执行主函数
main(); 